import { ref, watch } from 'vue'

/**
 * 本地存储管理组合式函数
 * @param {string} key 存储键名
 * @param {*} defaultValue 默认值
 * @param {Object} options 选项
 * @returns {Object} 存储值和方法
 */
export function useLocalStorage(key, defaultValue = null, options = {}) {
  const {
    serializer = JSON,
    syncAcrossTabs = true
  } = options

  // 读取存储值
  const read = () => {
    try {
      const item = localStorage.getItem(key)
      if (item === null) return defaultValue
      return serializer.parse(item)
    } catch (error) {
      console.warn(`读取localStorage失败: ${key}`, error)
      return defaultValue
    }
  }

  // 写入存储值
  const write = (value) => {
    try {
      if (value === null || value === undefined) {
        localStorage.removeItem(key)
      } else {
        localStorage.setItem(key, serializer.stringify(value))
      }
    } catch (error) {
      console.error(`写入localStorage失败: ${key}`, error)
    }
  }

  // 创建响应式引用
  const storedValue = ref(read())

  // 监听值变化并同步到localStorage
  watch(storedValue, (newValue) => {
    write(newValue)
  }, { deep: true })

  // 跨标签页同步
  if (syncAcrossTabs) {
    window.addEventListener('storage', (e) => {
      if (e.key === key && e.newValue !== serializer.stringify(storedValue.value)) {
        try {
          storedValue.value = e.newValue ? serializer.parse(e.newValue) : defaultValue
        } catch (error) {
          console.warn(`同步localStorage失败: ${key}`, error)
        }
      }
    })
  }

  // 移除存储
  const remove = () => {
    storedValue.value = null
  }

  // 重置为默认值
  const reset = () => {
    storedValue.value = defaultValue
  }

  return {
    value: storedValue,
    remove,
    reset
  }
}

/**
 * 用户偏好设置管理
 * @returns {Object} 用户偏好和方法
 */
export function useUserPreferences() {
  const defaultPreferences = {
    theme: 'light',
    language: 'zh-CN',
    pageSize: 20,
    autoSave: true,
    chartDefaults: {
      colors: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C'],
      animation: true,
      showLegend: true
    }
  }

  const { value: preferences, remove, reset } = useLocalStorage(
    'powerbi_user_preferences',
    defaultPreferences
  )

  const updatePreference = (key, value) => {
    preferences.value = {
      ...preferences.value,
      [key]: value
    }
  }

  const getPreference = (key, fallback = null) => {
    return preferences.value?.[key] ?? fallback
  }

  return {
    preferences,
    updatePreference,
    getPreference,
    remove,
    reset
  }
}



